from rest_framework.views import APIView
from rest_framework import status
from rest_framework.response import Response
from rest_framework import permissions
from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from libs.paginations import ListPagination
from .utils.pods_core import OprationPodsApi
from .utils.ingress_core import OprationIngressApi
from .utils.deployment_core import OprationDeploymentApi
from .utils.namespaces_core import OprationNamespacesApi



class NamespaceApiView(APIView):
    '''命名空间'''

    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (SessionAuthentication,JSONWebTokenAuthentication)

    def get(self,request,*args,**kwargs):
        '''获取命名空间列表  传参：{'namespace_name': str}， namespace_name: 命名空间名称'''

        namespace_list = OprationNamespacesApi().get_namespace_api()
        # 分页
        page_obj = ListPagination()
        results = page_obj.paginate_queryset(queryset=namespace_list,request=request,view=self)

        # 返回带超链接 需返回的时候用内置的响应方法
        return page_obj.get_paginated_response(results)


    def post(self,request,format=None):
        '''创建命名空间  传参：{'namespace_name': str}，  namespace_name: 为需要新建的命名空间名称'''

        namespace_name = self.request.data['namespace_name']
        namespace_obj = OprationNamespacesApi(namespace=namespace_name)

        return Response(namespace_obj.create_namespace_api())


    def delete(self,request,format=None):
        '''删除命名空间  传参：{'namespace_name': str}，  namespace_name: 为需要新建的命名空间名称'''

        namespace_name = self.request.query_params['namespace_name']
        namespace_obj = OprationNamespacesApi(namespace=namespace_name)

        return Response(namespace_obj.delete_namespace_api())



class PodsApiView(APIView):
    '''容器组'''

    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (SessionAuthentication, JSONWebTokenAuthentication)

    def get(self,request,*args,**kwargs):
        ''' 获取对应命名空间的所有容器组列表，传参：{'namespace_name' : str}   namespace_name: 为需要新建的命名空间名称.\n
            重启单个容器组实例，传参：{'namespace_name' : str, 'pod_name' : str}   pod_name: 为容器组名称.
        '''

        namespace_name = self.request.query_params['namespace_name']
        if len(namespace_name) <= 0:
            return Response({'msg':'namespace_name为必传参数'},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 对单个pod进行重启操作
        if 'pod_name' in self.request.query_params.keys():
            name = self.request.query_params['pod_name']
            pods_obj = OprationPodsApi(namespace=namespace_name)
            return Response(pods_obj.restart_pods_api(pod_name=name))

        # 实例化分页类
        page_obj = ListPagination()

        # 通过deployment名称搜索对应的pods列表
        if 'search' in self.request.query_params.keys() and len(self.request.query_params['search']) > 0:
            search_name = self.request.query_params['search']
            pods_list = OprationPodsApi(namespace=namespace_name).search_pods_api(search=search_name)
            results = page_obj.paginate_queryset(queryset=pods_list,request=request,view=self)
            return page_obj.get_paginated_response(results)

        # 获取所有pod列表
        pods_list = OprationPodsApi(namespace=namespace_name).get_pods_api()
        results = page_obj.paginate_queryset(queryset=pods_list, request=request, view=self)
        # 返回带超链接 需返回的时候用内置的响应方法
        return page_obj.get_paginated_response(results)


    def delete(self,request,*args,**kwargs):
        '''删除容器组  传参：{'namespace_name' : str, 'deployment_name' : str}'''

        namespace_name = self.request.query_params['namespace_name']
        deployment_name = self.request.query_params['deployment_name']

        # 通过删除对应的deployment去实现删除pod
        pods_obj = OprationDeploymentApi(namespace=namespace_name,deployment_name=deployment_name)
        return Response(pods_obj.delete_deployment_api())



class IngressApiView(APIView):
    '''路由'''

    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (SessionAuthentication, JSONWebTokenAuthentication)

    def get(self,request,*args,**kwargs):
        '''获取集群路由列表  传参：{'namespace_name': str}， namespace_name: 命名空间名称'''

        namespace_name = self.request.query_params['namespace_name']
        page_obj = ListPagination()

        # 通过ingress名称搜索对应的pods列表
        if 'search' in self.request.query_params.keys() and len(self.request.query_params['search']) > 0:
            search_name = self.request.query_params['search']
            ingress_list = OprationIngressApi(namespace=namespace_name,ingress_name=search_name).search_ingress_api()
            results = page_obj.paginate_queryset(queryset=ingress_list, request=request, view=self)
            return page_obj.get_paginated_response(results)

        # 获取ingress列表
        ingress_list = OprationIngressApi(namespace=namespace_name).get_ingress_api()
        # 分页
        results = page_obj.paginate_queryset(queryset=ingress_list,request=request,view=self)
        # 返回带超链接 需返回的时候用内置的响应方法
        return page_obj.get_paginated_response(results)


    def delete(self,request,*args,**kwargs):
        '''删除路由  传参：{'namespace_name' : str, 'ingress_name' : str}，ingress_name：路由名称.'''

        namespace_name = self.request.query_params['namespace_name']
        ingress_name = self.request.query_params['ingress_name']

        ingress_obj = OprationIngressApi(namespace=namespace_name,ingress_name=ingress_name)
        return Response(ingress_obj.delete_ingress_api())

    def post(self,request,*args,**kwargs):
        '''创建路由  传参：{‘namespace_name':str,'ingress_name':str,'service_name':str,'service_port':int,'domain':str}'''

        namespace_name = self.request.data['namespace_name']
        ingress_name = self.request.data['ingress_name']
        service_name = self.request.data['service_name']
        service_port = self.request.data['service_port']
        domain = self.request.data['domain']

        ingress_obj = OprationIngressApi(namespace=namespace_name,ingress_name=ingress_name)
        return Response(ingress_obj.create_ingress_api(service_name=service_name,service_port=service_port,domain=domain))



class DeploymentApiView(APIView):
    '''部署(deployment)'''

    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (SessionAuthentication, JSONWebTokenAuthentication)

    def post(self,request,*args,**kwargs):
        ''' 创建deployment，开发测试环境创建关联service及ingress.\n
            传参: {'namespace_name':str,'deployment_name':str,'port':int,'tag:str}.
        '''

        port = self.request.query_params['port']
        image_tag = self.request.query_params['tag']
        name = self.request.query_params['deployment_name']
        namespace_name = self.request.query_params['namespace_name']
        deployment_obj = OprationDeploymentApi(port=port,
                                               tag=image_tag,
                                               namespace=namespace_name,
                                               deployment_name=name
                                               )
        return Response(deployment_obj.create_deployment_api())

